//
//  FansViewController.m
//  yigou
//
//  Created by 秦乾龙 on 17/1/17.
//  Copyright © 2017年 hanyiwang. All rights reserved.
//

#import "FansViewController.h"
#import "ZYButton.h"
#import "User.h"
#import "HisHomePageViewController.h"
@interface FansViewController ()<UITextFieldDelegate,UITextViewDelegate,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,retain) UITableView *mainTableView;
@property (nonatomic,retain) NSMutableArray *allDataArr;
@property (assign, nonatomic) BOOL pageToEnd;
@property (assign, nonatomic) NSInteger page;
@property (assign, nonatomic) NSInteger limit;
@end

@implementation FansViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.page = 1;
    self.limit = 5;
    [ViewFactory setNavigationBlack:self];
    self.navigationItem.titleView = [ViewFactory makeNavigationTitle:@"粉丝"];
    
    UIBarButtonItem *backBtn = [ViewFactory makeNavigationBackWhite:self action:@selector(goPop)];
    self.navigationItem.leftBarButtonItem = backBtn;
     _allDataArr = [NSMutableArray array];
    [self setUI];
}
- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self request];
}

- (void) setUI
{
    _mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0,ScreenW , ScreenH-64) style:UITableViewStyleGrouped];
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    [self.view addSubview:_mainTableView];
    [self addRefreshHeader:_mainTableView];
    [self addLoadMoreFooter:_mainTableView];
}
//下拉刷新
- (void)refresh {
    [super refresh];
    [self request];
}
//上拉加载
- (void)loadMore {
    if (self.pageToEnd) {
        [ViewFactory showInfoMsg:@"没有下一页了！"];
        [_mainTableView.footer endRefreshing];
        return;
    }
    
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = [[NSString stringWithFormat:@"%@/userCenter/getAttountUserByUserId?page=%ld&limit=%ld", APIYIGOU, self.page,self.limit]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    request.requestUrl =  [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [ViewFactory showLoading];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
        NSArray *array = [[allDic objectForKey:@"data"] objectForKey:@"list"];
        if (array.count == 0) {
            [ViewFactory showInfoMsg:@"没有下一页了！"];
            
        }
        else if (array.count<_limit)
        {
            self.pageToEnd = YES;
        }
        self.page += 1;
        [_allDataArr addObjectsFromArray: array];
        [ViewFactory dismissLoading];
        [_mainTableView reloadData];
        [_mainTableView.footer endRefreshing];
    } error:^(YTKBaseRequest *request) {
        [_mainTableView.footer endRefreshing];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        [_mainTableView.footer endRefreshing];
    }];
}

- (void)request
{
    self.page = 1;
    self.pageToEnd = NO;
    NSString *urlStr = [[NSString stringWithFormat:@"%@/userCenter/getAttountUserByUserId?page=%ld&limit=%ld",APIYIGOU,self.page,self.limit]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    DYBaseRequest *request = [DYBaseRequest new];
    request.requestUrl = urlStr;
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
        NSLog(@"122222%@",allDic);
        [_allDataArr removeAllObjects];
        [_allDataArr addObjectsFromArray: allDic[@"data"][@"list"] ];
        
        [_mainTableView reloadData];
        self.page += 1;
        if (_allDataArr.count == 0) {
            [self showNoData];
        } else {
            [self hideNoData];
        }
        [_mainTableView.header endRefreshing];
    } error:^(YTKBaseRequest *request) {
        [_mainTableView.header endRefreshing];
    } failure:^(YTKBaseRequest *request) {
        [_mainTableView.header endRefreshing];
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _allDataArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell)
    {
        cell =[[NSBundle mainBundle ]loadNibNamed:@"ZYTableViewCell" owner:nil options:nil][0];
    }
    User *user = [[User alloc]initWithDic:_allDataArr[indexPath.section]];
    CGFloat headerImageH = 84*kScale;
    UIImageView *headerImage = [[UIImageView alloc]init];
    headerImage.frame = CGRectMake(30*kScale, 40*kScale,headerImageH, headerImageH);
    //        [headerImage sd_setImageWithURL:shop[@"seller_logo"]];
    headerImage.layer.masksToBounds = YES;
    headerImage.layer.cornerRadius = 42*kScale;
    //    headerImage.backgroundColor = [UIColor cyanColor];
    [headerImage sd_setImageWithURL:[NSURL URLWithString:user.headerImageUrl]];
    NSLog(@"99999%@",user.headerImageUrl);
    [cell addSubview:headerImage];
    UILabel *nameLable = [[UILabel alloc]init];
    nameLable.font = [UIFont systemFontOfSize:17];
    
    nameLable.text = user.name;
    nameLable.frame = CGRectMake(headerImageH+2*30*kScale, headerImage.frame.origin.y, ScreenW-(headerImageH+3*30*kScale), 36*kScale);
    [cell addSubview:nameLable];
    UILabel *introLable= [[UILabel alloc]init];
    introLable.font = [UIFont systemFontOfSize:15];
    introLable.text = [NSString stringWithFormat:@"%@",user.personSign];
    //        CGSize priceSize = [introLable sizeThatFits:CGSizeMake(MAXFLOAT, 40*kScale)];
    introLable.frame = CGRectMake(headerImageH+2*30*kScale, headerImage.frame.origin.y+headerImageH-40*kScale, ScreenW-3*30*kScale-headerImageH, 36*kScale);
    introLable.textColor = ZallColorFromRGB(0x616161);
    [cell addSubview:introLable];
    //时间
    UILabel *timeLable = [[UILabel alloc]init];
    NSDateFormatter  *dateFormatter = [[NSDateFormatter alloc]init];
    //        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:user.follow_tm];
    //            NSString *createDateStr = [NSString stringWithFormat:@"%ld",(long)[date timeIntervalSince1970]];
    NSDate *nowDate = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone]; // 获得系统的时区
    
    NSTimeInterval timeWrong = [zone secondsFromGMTForDate:nowDate];// 以秒为单位返回当前时间与系统格林尼治时间的差
    
    NSDate *dateNow = [nowDate dateByAddingTimeInterval:timeWrong];
    //            NSString *nowDateStr = [NSString stringWithFormat:@"%ld",(long)[nowDate timeIntervalSince1970]];
    NSTimeInterval time = [dateNow timeIntervalSinceDate:date];
    NSInteger time2 = time;
    
    if (time2/60/60/24>=1)
    {
        timeLable.text = [NSString stringWithFormat:@"%ld天之前关注了你",time2/60/60/24];
    }
    else if(time2/60/60>=1)
    {
        timeLable.text = [NSString stringWithFormat:@"%ld小时之前关注了你",time2/60/60];
    }
    else
    {
        timeLable.text = @"刚刚关注了你";
    }
    
    
    timeLable.font = [UIFont systemFontOfSize:12];
    CGSize timeLableSize = [timeLable sizeThatFits:CGSizeMake(MAXFLOAT, 42*kScale)];
    timeLable.frame = CGRectMake(ScreenW-30*kScale-timeLableSize.width, headerImage.frame.origin.y, ScreenW, timeLableSize.height);
    timeLable.textColor = ZallColorFromRGB(0x9e9e9e);
    [cell addSubview:timeLable];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return  164*kScale;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return  0.01;
    }
    
    return 20*kScale;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    User *user = [[User alloc]initWithDic:_allDataArr[indexPath.section]];
    HisHomePageViewController *hisHome = [[HisHomePageViewController alloc]init];
    hisHome.userid = user.userId;
    [self.navigationController pushViewController:hisHome animated:YES];
}
//返回
- (void)goPop
{
    [self.navigationController popViewControllerAnimated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
